package com.ruoyi.patrol.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.patrol.domain.PtGuard;
import com.ruoyi.patrol.domain.PtSchool;
import com.ruoyi.patrol.domain.PtSite;
import com.ruoyi.patrol.domain.PtStaff;
import com.ruoyi.patrol.mapper.PtGuardMapper;
import com.ruoyi.patrol.mapper.PtSiteMapper;
import com.ruoyi.patrol.mapper.PtStaffMapper;
import com.ruoyi.patrol.service.IPtSchoolService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学校信息Controller
 *
 * @author lkm
 * @date 2022-11-08
 */
@RestController
@RequestMapping("/patrol/school")
public class PtSchoolController extends BaseController {
    @Autowired
    private IPtSchoolService ptSchoolService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private PtStaffMapper staffMapper;

    @Autowired
    private PtGuardMapper guardMapper;

    @Autowired
    private PtSiteMapper siteMapper;

    /**
     * 查询学校信息列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:list')")
    @GetMapping("/list")
    public TableDataInfo list(PtSchool ptSchool) {
        startPage();
        List<PtSchool> list = ptSchoolService.selectPtSchoolList(ptSchool);
        return getDataTable(list);
    }

    /**
     * 查询学校信息列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:list')")
    @GetMapping("/listNum")
    public TableDataInfo listNum(PtSchool ptSchool) {
        startPage();
        List<PtSchool> list = ptSchoolService.selectPtSchoolStaffAndGuardNum(ptSchool);
        return getDataTable(list);
    }

    /**
     * 导出学校信息列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:export')")
    @Log(title = "学校信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PtSchool ptSchool) {
        List<PtSchool> list = ptSchoolService.selectPtSchoolList(ptSchool);
        ExcelUtil<PtSchool> util = new ExcelUtil<PtSchool>(PtSchool.class);
        return util.exportExcel(list, "school");
    }

    /**
     * 获取学校信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ptSchoolService.selectPtSchoolById(id));
    }

    /**
     * 获取学校信总数
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:query')")
    @GetMapping(value = "/count")
    public AjaxResult getSchoolCount() {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("schoolCount", ptSchoolService.selectSchoolCount());
        return ajax;
    }

    /**
     * 获取当前登录用户的学校名称
     *
     * @PreAuthorize("@ss.hasPermi('patrol:school:query')")
     */
    @GetMapping(value = "/info")
    public AjaxResult getSchoolNameAndPhone() {
        AjaxResult ajax = AjaxResult.success();
        Long schoolId = SecurityUtils.getSchoolId();
        if (schoolId == null) {
            ajax.put("schoolName", "");
            ajax.put("phonenumber", "");
            return ajax;
        }
        PtSchool ptSchool = ptSchoolService.selectPtSchoolById(schoolId);
        if (ptSchool == null) {
            ajax.put("schoolName", "");
            ajax.put("phonenumber", "");
            return ajax;
        }
        ajax.put("schoolName", ptSchool.getName());
        ajax.put("phonenumber", ptSchool.getUrgentPhone());
        return ajax;
    }

    /**
     * 新增学校信息
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:add')")
    @Log(title = "学校信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PtSchool ptSchool) {
        SysUser sysUser = userMapper.checkPhoneUnique(ptSchool.getSysUser().getPhonenumber());
        if (!ObjectUtils.isEmpty(sysUser)) {
            return AjaxResult.error("新增学校'" + ptSchool.getName() + "'失败，责任人手机号码已存在");
        }
        PtSchool school = ptSchoolService.selectPtSchoolByName(ptSchool.getName());
        if (!ObjectUtils.isEmpty(school)) {
            return AjaxResult.error("新增学校'" + ptSchool.getName() + "'失败，学校名称已存在");
        }
        return toAjax(ptSchoolService.insertPtSchool(ptSchool));
    }

    /**
     * 修改学校信息
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:edit')")
    @Log(title = "学校信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PtSchool ptSchool) {
        PtSchool school = ptSchoolService.selectPtSchoolById(ptSchool.getId());
        if (!school.getSysUser().getPhonenumber().equals(ptSchool.getSysUser().getPhonenumber())) {
            SysUser sysUser = userMapper.checkPhoneUnique(ptSchool.getSysUser().getPhonenumber());
            if (!ObjectUtils.isEmpty(sysUser)) {
                return AjaxResult.error("修改学校'" + ptSchool.getName() + "'失败，手机号码已存在");
            }
        }
        if (!school.getName().equals(ptSchool.getName())) {
            PtSchool school1 = ptSchoolService.selectPtSchoolByName(ptSchool.getName());
            if (!ObjectUtils.isEmpty(school1)) {
                return AjaxResult.error("修改学校'" + ptSchool.getName() + "'失败，学校名称已存在");
            }
        }
        return toAjax(ptSchoolService.updatePtSchool(ptSchool));
    }

    /**
     * 删除学校信息
     */
    @PreAuthorize("@ss.hasPermi('patrol:school:remove')")
    @Log(title = "学校信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        PtStaff staff = new PtStaff();
        staff.setSchoolId(ids[0]);
        List<PtStaff> ptStaffs = staffMapper.selectPtStaffList(staff);
        if (!CollectionUtils.isEmpty(ptStaffs)) {
            return AjaxResult.error("该学校存在行政人员，无法删除");
        }
        PtGuard guard = new PtGuard();
        guard.setSchoolId(ids[0]);
        List<PtGuard> ptGuards = guardMapper.selectPtGuardList(guard);
        if (!CollectionUtils.isEmpty(ptGuards)) {
            return AjaxResult.error("该学校存在安保人员，无法删除");
        }
        PtSite site = new PtSite();
        site.setSchoolId(ids[0]);
        List<PtSite> ptSites = siteMapper.selectPtSiteList(site);
        if (!CollectionUtils.isEmpty(ptSites)) {
            return AjaxResult.error("该学校存在巡逻点位信息，无法删除");
        }
        return toAjax(ptSchoolService.deletePtSchoolByIds(ids));
    }
}
